package cn.orangelite.ai.controller;

import cn.hutool.core.io.IoUtil;
import cn.orangelite.ai.domain.AiGptKey;
import cn.orangelite.ai.domain.AiGptMessageLog;
import cn.orangelite.ai.domain.dto.ChatBodyDTO;
import cn.orangelite.ai.domain.dto.ChatDTO;
import cn.orangelite.ai.domain.dto.Message;
import cn.orangelite.ai.service.IAiGptKeyService;
import cn.orangelite.ai.service.IAiGptMessageLogService;
import cn.orangelite.common.core.utils.poi.ExcelUtil;
import cn.orangelite.common.core.web.controller.BaseController;
import cn.orangelite.common.core.web.domain.AjaxResult;
import cn.orangelite.common.core.web.page.TableDataInfo;
import cn.orangelite.common.log.annotation.Log;
import cn.orangelite.common.log.enums.BusinessType;
import cn.orangelite.common.redis.service.RedisService;
import cn.orangelite.common.security.annotation.RequiresPermissions;
import cn.orangelite.common.security.utils.SecurityUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.List;

/**
 * gptkey
 Controller
 *
 * @author dongfaqing
 * @date 2024-01-16
 */
@RestController
@RequestMapping("/gpt")
public class AiGptKeyController extends BaseController
{
    @Autowired
    private IAiGptKeyService aiGptKeyService;

    @Autowired
    private RedisService redisService;

    @Autowired
    private IAiGptMessageLogService aiGptMessageLogService;

    /**
     * 查询gptkey
     列表
     */
    @RequiresPermissions("ai:key:list")
    @GetMapping("/list")
    public TableDataInfo list(AiGptKey aiGptKey)
    {
        startPage();
        List<AiGptKey> list = aiGptKeyService.selectAiGptKeyList(aiGptKey);
        return getDataTable(list);
    }

    /**
     * 导出gptkey
     列表
     */
    @RequiresPermissions("ai:gpt:export")
    @Log(title = "gptkey", businessType = BusinessType.EXPORT)
            @PostMapping("/export")
            public void export(HttpServletResponse response, AiGptKey aiGptKey)
    {
        List<AiGptKey> list = aiGptKeyService.selectAiGptKeyList(aiGptKey);
        ExcelUtil<AiGptKey> util = new ExcelUtil<AiGptKey>(AiGptKey.class);
        util.exportExcel(response, list, "gptkey数据");
    }

    /**
     * 获取gptkey
     详细信息
     */
    @RequiresPermissions("ai:gpt:query")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return success(aiGptKeyService.selectAiGptKeyById(id));
    }

    /**
     * 新增gptkey

     */
    @RequiresPermissions("ai:gpt:add")
    @Log(title = "gptkey", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody AiGptKey aiGptKey){
        if(aiGptKey.getState()==0){
            AiGptKey otherKeys = new AiGptKey();
            otherKeys.setState(1L);
            aiGptKeyService.update(otherKeys,Wrappers.<AiGptKey>lambdaQuery().eq(AiGptKey::getType,aiGptKey.getType()).eq(AiGptKey::getState,0));
        }
        return toAjax(aiGptKeyService.insertAiGptKey(aiGptKey));
    }

    /**
     * 修改gptkey

    */
    @RequiresPermissions("ai:gpt:edit")
    @Log(title = "gptkey", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody AiGptKey aiGptKey){
        if(aiGptKey.getState()==0){
            AiGptKey otherKeys = new AiGptKey();
            otherKeys.setState(1L);
            aiGptKeyService.update(otherKeys,Wrappers.<AiGptKey>lambdaQuery().eq(AiGptKey::getType, aiGptKey.getType()).eq(AiGptKey::getState,0));
        }
        return toAjax(aiGptKeyService.updateAiGptKey(aiGptKey));
    }

    /**
     * 删除gptkey

    */
    @RequiresPermissions("ai:gpt:remove")
    @Log(title = "gptkey", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(aiGptKeyService.deleteAiGptKeyByIds(ids));
    }


    /**
     * 发送聊天
     * @param chatDTO
     * @return
     */
//    @PostMapping("/chat")
//    public AjaxResult chat(@RequestBody ChatDTO chatDTO) {
//        try{
//            Integer logId = aiGptKeyService.gptChat(chatDTO);
//            return success(logId);
//        }catch (Exception e){
//            return error("请求失败");
//        }
//    }

    @PostMapping("/wechatGpt")
    public AjaxResult wechatGpt(HttpServletRequest req, HttpServletResponse response,@RequestBody ChatBodyDTO chatBodyDTO) throws IOException {
        return success(aiGptKeyService.wechatGpt(chatBodyDTO));

//        InputStream inputStream = aiGptKeyService.wechatGpt(chatBodyDTO);
//
//        response.setContentType("text/event-stream");
//        response.setCharacterEncoding("UTF-8");
////        PrintWriter out = response.getWriter();
//
//        // 获取输出流
//        byte[] buffer = new byte[1024];
//        int bytesRead;
//        while ((bytesRead = inputStream.read(buffer)) != -1) {
//            // 将数据写入到 Servlet 响应中
//            response.getOutputStream().write(buffer, 0, bytesRead);
//            // 刷新输出流，确保数据被立即发送到客户端
//            response.flushBuffer();
//        }
//
//        // 关闭输入流
//        IoUtil.close(inputStream);
    }


    /**
     * 获取聊天记录
     * @return
     */
    @GetMapping("/getMessageLog")
    public TableDataInfo getMessageLog(){
        startPage();
        List<AiGptMessageLog> list = aiGptMessageLogService.list(Wrappers.<AiGptMessageLog>lambdaQuery().eq(AiGptMessageLog::getUserId, SecurityUtils.getUserId()).orderByDesc(AiGptMessageLog::getCreateTime));
        return getDataTable(list);
    }

    /**
     * 返回完整消息后保存
     */
    @PostMapping("/saveMssageLog/{logId}")
    public AjaxResult saveMessageLog(@PathVariable("logId") Integer logId,@RequestBody Message message){

        aiGptMessageLogService.saveMessageLog(logId,message);

        return success();
    }


    @PostMapping("delLog")
    public AjaxResult delLog(@RequestBody ChatDTO chatDTO){
        aiGptMessageLogService.removeById(chatDTO.getLogId());
        return success();
    }


}
